package com.springboot.sba.D5_MySql.service;

import com.alibaba.fastjson.JSONObject;
import com.springboot.sba.D5_MySql.dao.GpMapper;
import com.springboot.sba.bean.Gp;
import com.springboot.sba.bean.GpHistory;
import com.springboot.sba.utils.HttpRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: ZZZ
 * @time: 2021/12/6 14:16
 */
@Component
public class GpHistoryService {

    @Autowired
    private GpMapper gpMapper;

    @PostConstruct
    public void init() {
        String startDate="20211202";
        String endDate="20211202";
        LocalDateTime s= LocalDateTime.now();
        List<GpHistory> batch = new ArrayList<>();
        List<Gp> gpList = gpMapper.getCode();

        gpList.forEach(x -> {
            String code=x.getCode();
            String url = String.format("https://q.stock.sohu.com/hisHq?code=cn_%s&start=%s&end=%s",code,startDate,endDate);
            String result = HttpRequestUtil.httpRequest(url);
            if (result.length() > 30) {
                List<Map<String, Object>> hqList = new ArrayList<>();
                hqList = JSONObject.parseObject(result, List.class);
                String status = hqList.get(0).get("status").toString();
                if("0".equals(status)){
                    String hq = hqList.get(0).get("hq").toString();
                    hq = hq.substring(1, hq.length() - 1);
                    List<String> list = new ArrayList<>();
                    list = JSONObject.parseObject(hq, List.class);

                    String day = list.get(0);
                    String open = list.get(1);
                    String close = list.get(2);
                    String increase = list.get(3);
                    String increase_p = list.get(4);
                    increase_p = increase_p.substring(0, increase_p.length() - 1);
                    String low = list.get(5);
                    String high = list.get(6);
                    String volume = list.get(7);

                    String name=x.getName();

                    GpHistory history = new GpHistory(code,name,open, close, increase, increase_p, low, high, volume, day);
                    batch.add(history);
                    System.out.println(x+"  "+hq);
                }
            }
        });

        LocalDateTime e= LocalDateTime.now();
        long seconds1 = Duration.between(s, e).getSeconds();

        LocalDateTime ss= LocalDateTime.now();
        gpMapper.historyBatchInsert(batch);
        LocalDateTime ee= LocalDateTime.now();
        long seconds2 = Duration.between(ss, ee).getSeconds();
        System.out.println("查询"+batch.size()+"条 用时："+seconds1);
        System.out.println("批量插入"+batch.size()+"条 用时："+seconds2);
    }
}
